package com.cat.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.cat.util.ServletUtils.showError;

/**
 * @author :HYC  email: kobe524348@gmail.com
 * @program : HYC_CatRecruit
 * @name : AdminFilter
 * @description : a filter to check if the user is an administrator
 * @create : 2019-03-26 20:53
 */
@WebFilter("/AdminServlet")
public class AdminFilter implements Filter {

    private String ENCODING =null;

    @Override
    public void init(FilterConfig config){
        this.ENCODING= config.getInitParameter("ENCODING");
    }

    @Override
    public void destroy() {

    }

    /**
     * @name doFilter
     * @description 测试文档中的提示信息
     * 测试在下一行中书写提示信息
     * @param  servletRequest 第一个参数
     * @param servletResponse 第二个参数
     * @param filterChain 测试文档注释
     * @notice
     * @author HYC kobe524348@gmail.com
     * @date 2019/3/30
     */
    @Override
     public void  doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        HttpSession sess = req.getSession();
        System.out.println("com.cat.filter.AdminFilter : doFilter......");
        //检查是否登陆
        if (sess.getAttribute("login") == null) {
            //重定向到登陆页面
            System.out.println("com.cat.filter.AdminFilter : login = null");
            res.sendRedirect("login.jsp");
        } else if (req.getAttribute("admin") == null &&sess.getAttribute("admin") == null) {
            //重定向到错误页面
            showError(req,res,"权限错误 : 您没有权限进行此操作","解决方案：只有管理员有权进行此操作，您并不是管理员用户，请进入您的个人中心查看和修改您的个人信息");
        } else {
            System.out.println("com.cat.filter.AdminFilter : pass! ");
            filterChain.doFilter(req,res);
        }
    }

}
